﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using MiniCrawler.DataAccess;
using MiniCrawler.DataAccess.Repositories;
using MiniCrawler.Entity;
using MiniCrawler.UrlFilter;

namespace MiniCrawler.Downloader.ResourceDownloader
{
    public class NastyCloth : ResourceLinkCollector, IResourceCollector
    {
        private string hostName;

        public NastyCloth(string hostName, int level)
            : base(hostName, level)
        {
            this.hostName = hostName;
        }

        public string GetFolderPath(string data)
        {
            // Load data
            var doc = new HtmlDocument();
            doc.LoadHtml(data);


            var textString =
                "/html" +
                "/body" +
                "/div[@class='page']" + 
                "/div[@class='site-content']" ;

            var path = doc.DocumentNode.SelectSingleNode(textString);

            var breadCums = path.SelectNodes("div[@id='main-container']/ul[@class='breadcrumb']/li");

            var breadCumString = string.Empty;
            foreach (var breadCum in breadCums)
            {
                breadCumString += breadCum.InnerText + "\\";
            }

            // Processing text
            // \ / : | ? * "
            string processedText =
                (breadCumString)
                    .Replace("&gt;", ">")
                    .Replace("&raquo;", ">")
                    .Replace("&amp;", "-")
                    .Replace(">", "\\")
                    .Replace("»", "\\")
                    .Replace('&', '-')
                    .Replace("/", string.Empty)
                    .Replace("|", string.Empty)
                    .Replace("?", string.Empty)
                    .Replace("*", string.Empty)
                    .Replace("\"", string.Empty)
                    .Replace(":", string.Empty)
                    .Replace("\r", string.Empty)
                    .Replace("\n", string.Empty)
                    .Replace("\t", string.Empty);
            if (processedText.Length > 255) processedText = processedText.Substring(0, 255);
            if (!string.IsNullOrEmpty(processedText))
                return processedText;
            else return "/";
        }

        public List<string> GetAllLinks(string data)
        {
            // Load data
            var doc = new HtmlDocument();
            doc.LoadHtml(data);
            
            var textString =
                "/html" +
                "/body" +
                "/div[@class='page']" +
                "/div[@class='site-content']" +
                "/div[@id='main-container']" +
                "/div[@class='product-detail-container row-fluid']" +
                "/div[@class='col-left span9']/div[@class='product-images-wrapper']" +
                "/div[@class='product-images']/div[@class='carousel']" +
                "/ul[@id='product-images-carousel']/li/img";

            var imgs = doc.DocumentNode.SelectNodes(textString);

            List<string> images = new List<string>();

            if(imgs != null && imgs.Count >0)
            {
                foreach (var img in imgs)
                {
                    var src = Utils.GetAttribute(img, "src");

                    if (src.StartsWith("//"))
                        src = "http:" + src;

                    images.Add(src);
                }
            }
            


            return images;
        }

        private List<string> FindStringBetween(string source, string start, string end)
        {
            var t = source.IndexOf(start);
            var result = new List<string>();

            while (t != null && t != -1)
            {
                string cutsource = source.Substring(t, source.Length - t);
                var z = cutsource.IndexOf(end);
                if (z != null && z != t)
                {
                    var s = cutsource.Substring(0, z);
                    cutsource = cutsource.Replace(s, string.Empty);
                    result.Add(s);
                    source = cutsource;
                    t = source.IndexOf(start);
                }
            }

            return result;
        }

        public List<string> GetResourcePatterns()
        {
            return new List<string>();
        }

        public void GetLinks()
        {
            foreach (var dataLink in Urls)
            {
           
            string data = Common.GetWebPage(Common.FillAbsoluteUrl(hostName, dataLink.Value));
            if (!string.IsNullOrEmpty(data))
            {
                string folderPath = GetFolderPath(data);
                var allLinks = GetAllLinks(data);

                if (allLinks != null && allLinks.Count > 0)
                {
                    foreach (var link in allLinks)
                    {
                        var downloadLink =
                            new DownloadLink
                            {
                                Path = folderPath,
                                Value = link,
                                Website = dataLink.Website,
                                IsDownloaded = false,
                                Url = dataLink.Value
                            };
                        DownloadLinkHelper.CreateLink(downloadLink);
                    }
                }

                DataLinkHelper.UpdateLink(dataLink.Value);
            }
            }

            
        }

        public void FixUrls()
        {
            DownloadLinkHelper.FixPathUrl(hostName);
        }
    }
}
